#include "command.h"

void command_cd(command_t *cod, int netFD, MYSQL *conn, client_t *clt){
    //cd ..  cd dir
    if(strcmp(cod->path, "..") == 0){
        //返回上一级目录
        char buf1[1024] = { 0 };
        sprintf(buf1, "select id, path from file where id = (select father_id from file where id = %d)", clt->file_id);
        char strr[2][1024] = { {0} };
        int num = mysql_select_get_one_row(conn, buf1, strr);
        if(num == -1 || num == 0){
            int ret = -1;
            send(netFD, &ret, sizeof(ret), MSG_NOSIGNAL);
            return;
        }
        clt->file_id = atoi(strr[0]);
        bzero(clt->dir_path, sizeof(clt->dir_path));
        strcpy(clt->dir_path, strr[1]);
        //存在上一级目录
        int ret = 1;
        send(netFD, &ret, sizeof(ret), MSG_NOSIGNAL);
    }else{
        char path[1024] = { 0 };
        if(strcmp(clt->dir_path, "/") == 0){
            sprintf(path, "/%s", cod->path);
        }else{
            sprintf(path, "%s/%s", clt->dir_path, cod->path);
        }
        char buf1[2048] = { 0 };
        sprintf(buf1, "select id from file where path = '%s' and user_name = '%s'", path, clt->name);
        char str[20] = { 0 };
        int num = mysql_select_get_one_str(conn, buf1, str);
        if(num == -1 || num == 0){
            int ret = -1;
            send(netFD, &ret, sizeof(ret), MSG_NOSIGNAL);
            return;

        }
        clt->file_id = atoi(str);
        bzero(clt->dir_path, sizeof(clt->dir_path));
        strcpy(clt->dir_path, path);
        int ret = 1;
        send(netFD, &ret, sizeof(ret), MSG_NOSIGNAL);
    }
}
